package com.modular.extra.fm.online.opt;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.c.opt.ComOpt;
import com.modular.extra.fm.FactoryFmOpt;
import com.modular.extra.fm.online.bean.OnLineDo;
import ntd.util.ToolLock;
import ntd.util.frame.task.handle.fm.util.ToolFmData;

/**
 * 离线记录操表
 */
public class OptOnline extends ComOpt<OnLineDo> {

    public OptOnline() {
        super("on_off_record", FactoryFmOpt.DS_ID);
    }

    /**
     * 设备在线
     * @param mn
     */
    public void onLine(String mn) {
        if (StrUtil.isBlank(mn)) {
            return;
        }
        ToolLock.lockRun("OptOnline-online" + mn, () -> {
            OnLineDo bean = query().eq("mn", mn).isNull("on_time").getBean();
            Opt.ofNullable(bean).ifPresent(onLineDo -> {
                onLineDo.setOnTime(LocalDateTimeUtil.now());
                syncBean(onLineDo);
            });
        });
    }

    /**
     * 设备离线
     * @param mn
     */
    public void offLine(String mn) {
        if (StrUtil.isBlank(mn)) {
            return;
        }
        ToolLock.lockRun("OptOnline-offLine" + mn, () -> {
            OnLineDo lineDo = Opt.ofNullable(query().eq("mn", mn).isNull("on_time").getBean()).orElseGet(() -> {
                OnLineDo onLineDo = new OnLineDo();
                onLineDo.setMn(mn);
                return onLineDo;
            });
            lineDo.setOffTime(LocalDateTimeUtil.now());
            syncBean(lineDo);
        });
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            ThreadUtil.execAsync(() -> {
                ToolFmData.OPT_FM_ON_LINE.offLine("41010501G00001");
            });
            ThreadUtil.execAsync(() -> {
                ToolFmData.OPT_FM_ON_LINE.offLine("41010501G00001");
            });
            ThreadUtil.execAsync(() -> {
                ToolFmData.OPT_FM_ON_LINE.offLine("41010501G00001");
            });
        }
    }

}
